package com.tql.mall.order.receiver;

import com.rabbitmq.client.Channel;
import com.tql.mall.model.enums.OrderStatus;
import com.tql.mall.model.enums.ProcessStatus;
import com.tql.mall.model.order.OrderInfo;
import com.tql.mall.order.service.OrderService;
import com.tql.mall.rabbit.constant.MqConstant;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: tyk
 * @Date: 2023/5/27 11:56
 * @Description:
 */
@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    /**
     * 超时取消订单
     */
    @SneakyThrows
    @RabbitListener(queues = MqConstant.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId, Message msg, Channel channel) {
        try {
            // 已支付则不进行操作，未支付则取消订单
            if (orderId != null) {
                // 查询订单
                OrderInfo orderInfo = orderService.getById(orderId);
                if (orderInfo != null) {
                    if (OrderStatus.UNPAID.name().equals(orderInfo.getOrderStatus()) &&
                            ProcessStatus.UNPAID.name().equals(orderInfo.getProcessStatus())) {
                        // 处理过期订单
                        orderService.execExpireOrder(orderId);
                    }
                }
            }
        } catch (Exception e) {
            // 写入日志、通知维护人员
        }
        channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 支付成功更新订单消息队列
     */
    @SneakyThrows
    @RabbitListener(queues = MqConstant.QUEUE_PAY)
    public void paySuccess(Long orderId, Message msg, Channel channel) {
        try {
            // 支付成功修改订单状态
            if (orderId != null) {
                OrderInfo orderInfo = orderService.getOrderInfo(orderId);
                if (orderInfo != null && OrderStatus.UNPAID.name().equals(orderInfo.getOrderStatus())) {
                    // 先修改父订单状态（修改成待发货）
                    orderService.updateOrderStatus(orderId, ProcessStatus.WAIT_DELIVER);
                    // 再拆单
                    orderService.splitOrder(orderInfo);
                }
            }
        } catch (Exception e) {
            // 写入日志、通知维护人员
        }
        channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
    }

}
